<?php
//支付宝手机网站支付 回调地址
// 授权回调地址，将用户的UID与授权返回码存入

/*1、连接数据库 
        端口号或者地址 
        登录数据库的登录名
        登录密码
        要操作的数据库名
        */


if ($_POST) {
    $val = '---------------------POST异步通知----------------<br>';
    $val .= json_encode($_POST);
    $val .= $update;
    $val .= '-------------------------------------------------<br>';
} else {
    $val = '------------------------GET通知-------------------<br>';
    $val .= json_encode($_GET);
    $val .= '-------------------------------------------------<br>';
}

file_put_contents("shouji.txt", $val . PHP_EOL, FILE_APPEND);

$link = mysqli_connect('127.0.0.1', 'ali', 'ali', 'ali', '3306');
if (!$link) {

}

//2、选择要操作的数据库
mysqli_select_db($link, 'ali');
//3、设置交互编码
mysqli_query($link, 'set names utf8');
$time = time();

// 高级支付高级支付高级支付高级支付高级支付


if ($_POST['trade_status'] == 'TRADE_SUCCESS') {//交易成功
    // 保存数据操作 1、将订单状态修改为成功；2、修改平台用户的余额；


        // 1、将订单状态修改为成功
    $danhao = $_POST['out_trade_no'];

    $select = "select * from `jd_dingdan` where `danhao`='{$danhao}' limit 1";
    // $select="select * from `jd_kbsh` where `uid`=222";
    $arr = mysqli_query($link, $select);
    $one = mysqli_fetch_assoc($arr);

    if ($one['status'] == 1) {
        file_put_contents("xykResult.txt", date('Y-m-d H:i:s').' 订单状态已修改' . PHP_EOL, FILE_APPEND);

    } else {
        $trade_no = $_POST['trade_no'];
        $buyer = $_POST['buyer_logon_id'];
        $seller = $_POST['seller_email'];
        $money = $_POST['total_amount'];
        $buyer_id = $_POST['buyer_id'];
        // gather
        $uid = $one['uid'];

        $select = "select * from `jd_gather` where `uid`={$uid} limit 1";

        $arr = mysqli_query($link, $select);
        $gather = mysqli_fetch_assoc($arr); //用户

        if ($one['hk'] == 1) {//不回款--手动
            $yh_money = $money * (100 - $gather['up_set2']) / 100;
        } else {
            //用户订单收益 = 订单金额 × （回款费率 - 上级设定费率）
	    	$yh_money   =$money*($gather['path5']-$gather['up_set2'])/100; //回款



        }

//        $total = $gather['money'] + $yh_money;
        $total = $gather['fenrun'] + $yh_money;
        $total = number_format($total, 2, '.', '');
        $update = "update `jd_dingdan` set `trade_no`='{$trade_no}',`buyer`='{$buyer}',`seller`='{$seller}',`status`=1,`pay_money`={$money},`yh_money`='{$yh_money}' where `danhao`='{$danhao}'";

        $id = mysqli_query($link, $update);

        if ($id > 0) {
            file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'订单状态修改成功' . PHP_EOL, FILE_APPEND);

            // 2、修改平台用户的余额；
            // $select="select * from `jd_dingdan` where `danhao`='{$danhao}' limit 1";
            // // $select="select * from `jd_kbsh` where `uid`=222";
            // $arr=mysqli_query($link,$select);
            // $one=mysqli_fetch_assoc($arr);
            // 判断是否要回款 不回款的用户余额=总*(1-费率)/100 -2
            $total_money = floatval($total)+floatval($gather['yongjin']);
//            $update = "update `jd_dingdan` set `t_money`='{$total}' where `danhao`='{$danhao}'";
            $update = "update `jd_dingdan` set `t_money`='{$total_money}' where `danhao`='{$danhao}'";

            mysqli_query($link, $update);
            // 修改平台用户余额
//            $update = "update `jd_gather` set `money`={$total} where `uid`={$uid}";
            $update = "update `jd_gather` set `fenrun`={$total} where `uid`={$uid}";
            $re = mysqli_query($link, $update);
            if ($re > 0) {
                file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'平台用户余额修改成功' . PHP_EOL, FILE_APPEND);

                if ($one['hk'] == 1) {
                    //不回款不需制定
                } else {
                    // 插播：制定对应的回款表
//                    $trans_money = $money * (1 - $gather['path5'] / 100);
                    //修改为 收款码设置的费率

                    //取出收款码回款费率
                    $shoukuanma_id = $one['shoukuanma_id'];
                    $select = "select * from `jd_shoukuanma` WHERE `id` = '{$shoukuanma_id}'";
                    $arr = mysqli_query($link, $select);
                    $shoukuanma = mysqli_fetch_assoc($arr);

                    $trans_money = $money * (1 - $shoukuanma['xyk'] / 100);
                    $trans_money = number_format($trans_money, 2, '.', '');
                    //回款金额 = 订单金额 ×（100- 回款费率）

                    $out_biz_no = 'xy' . date("YmdHis") . rand(1000, 9999);
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'pay_return2.php回款金额信息'.$trans_money . PHP_EOL, FILE_APPEND);

                    $add = "insert into `jd_trans` (`trade_no`,`uid`,`money`,`buyer_id`,`out_biz_no`,`shoukuanma_id`,`account`) values ('{$trade_no}','{$uid}','{$trans_money}','{$buyer_id}','{$out_biz_no}','{$shoukuanma_id}','{$money}')";
                    $trans_result = mysqli_query($link, $add);
                    if($trans_result){

                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'回款表写入成功' . PHP_EOL, FILE_APPEND);
                    }else{
                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'回款表写入失败' . PHP_EOL, FILE_APPEND);
                    }

                    //为给自己增加分润
                    $selfDivide = $money * ($shoukuanma['xyk'] - $gather['up_set2']) / 100;
                    $selfDivide = number_format($selfDivide, 2, '.', '');
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '给自己分润金额: ' . $selfDivide . PHP_EOL, FILE_APPEND);

                    $add = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`,`divide`,`time`,`status`) values ('{$uid}','{$danhao}','{$trade_no}','{$uid}','','{$money}',2,0,'{$selfDivide}',$time,1)";
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '给自己分润金额sql: ' . $add . PHP_EOL, FILE_APPEND);

                    $selfDivideAddRes = mysqli_query($link, $add);

                    if ($selfDivideAddRes) {

                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '给自己分润成功' . PHP_EOL, FILE_APPEND);
                    } else {
                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '给自己分润失败' . PHP_EOL, FILE_APPEND);
                    }
                }
                // echo success;
                // 4、查询是否有上级 有的话需要给上级的余额增加该笔订单的%
                $select = "select * from `jd_ptyh` where `uid`={$one[uid]} limit 1";
                $arr = mysqli_query($link, $select);
                $ptyh = mysqli_fetch_assoc($arr);  //当前用户

                if ($ptyh['pid'] == 0 || $ptyh['level'] > 6) {//没有上级+4级以下
                    echo success;
                } else {
                    // 查找上一级

                    //信用卡团队奖励团队奖励金

                    $select = "select * from `jd_ptdata` where `id`=1";
                    $arr = mysqli_query($link, $select);
                    $ptdata = mysqli_fetch_assoc($arr);
                    $xyk_jiangli = $ptdata['xyk_jiangli'];

                    /** 父级 start */
                    $select = "select * from `jd_ptyh` where `uid`={$ptyh[pid]} limit 1";
                    $arr = mysqli_query($link, $select);
                    $parentPtyh = mysqli_fetch_assoc($arr);  //当前用户的上级

                    $select = "select * from `jd_gather` WHERE `uid`={$ptyh[pid]} limit 1";
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '上级分润sql：'. $select . PHP_EOL, FILE_APPEND);

                    $arr = mysqli_query($link, $select);
                    $fatherGather = mysqli_fetch_assoc($arr);
                    $firstLevelDivide = $money * ($gather['up_set2'] - $fatherGather['up_set2']) / 100;
                    $firstLevelDivide = number_format($firstLevelDivide, 2, '.', '');
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '上级分润金额：'. $firstLevelDivide . PHP_EOL, FILE_APPEND);


                    $shou = $one['uid'];
                    $parent = $parentPtyh['uid'];
                    $danhao = 'xy' . date("YmdHis") . rand(1000, 9999);


                    /** 爷爷级  start */
                    $grandfatherSql = "select * from `jd_ptyh` WHERE `uid` = {$parentPtyh[pid]} limit 1";
                    $grandfatherArr = mysqli_query($link, $grandfatherSql);
                    $grandfather = mysqli_fetch_assoc($grandfatherArr);

                    $select = "select * from `jd_gather` WHERE `uid`={$parentPtyh[pid]} limit 1";
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '上上级sql：'. $select . PHP_EOL, FILE_APPEND);

                    $arr = mysqli_query($link, $select);
                    $grandfatherGather = mysqli_fetch_assoc($arr);
                    $secondLevelDivide = $money * ($fatherGather['up_set2'] - $grandfatherGather['up_set2']) / 100;
                    $secondLevelDivide = number_format($secondLevelDivide, 2, '.', '');
                    $grandfatherUid = $grandfather['uid'];
                    /** 爷爷级 end */


                    $add = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`,`time`,`divide`,`status`) values ('{$parent}','{$danhao}','{$trade_no}','{$shou}','{$parent}','{$money}',2,1,$time,$firstLevelDivide,1),('{$parent}','{$danhao}','{$trade_no}','{$shou}','{$parent}',{$money},3,1,$time,'{$xyk_jiangli}',1),('{$grandfatherUid}','{$danhao}','{$trade_no}','{$shou}','{$grandfatherUid}','{$money}',2,2,$time,$secondLevelDivide,1),('{$grandfatherUid}','{$danhao}','{$trade_no}','{$shou}','{$grandfatherUid}',{$money},3,2,$time,'{$xyk_jiangli}',1)";
                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '给上级分sql' . $add . PHP_EOL, FILE_APPEND);
//
                    $id4 = mysqli_query($link, $add);
//                    //每笔信用卡订单给父级提0.5
//                    $fatherticheng = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`,`time`,`divide`,`status`) values ('{$parent}','{$danhao}','{$trade_no}','{$shou}','{$parent}',{$money},3,1,$time,'0.5',1)";
//                    mysqli_query($link, $fatherticheng);
                    /** 父级 end */



                    /** 爷爷级  start */
//                    $grandfatherSql = "select * from `jd_ptyh` WHERE `uid` = {$parentPtyh[pid]} limit 1";
//                    $grandfatherArr = mysqli_query($link, $grandfatherSql);
//                    $grandfather = mysqli_fetch_assoc($grandfatherArr);
//
//                    $select = "select * from `jd_gather` WHERE `uid`={$parentPtyh[pid]} limit 1";
//                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '上上级sql：'. $select . PHP_EOL, FILE_APPEND);
//
//                    $arr = mysqli_query($link, $select);
//                    $grandfatherGather = mysqli_fetch_assoc($arr);
//                    $secondLevelDivide = $money * ($fatherGather['up_set2'] - $grandfatherGather['up_set2']) / 100;
//                    $secondLevelDivide = number_format($secondLevelDivide, 2, '.', '');
//                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '上上级分润金额：'. $secondLevelDivide . PHP_EOL, FILE_APPEND);
//
//
//                    $grandfatherUid = $grandfather['uid'];
//                    $grandfatherDividend = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`,`time`,`divide`,`status`) values ('{$grandfatherUid}','{$danhao}','{$trade_no}','{$shou}','{$grandfatherUid}','{$money}',2,2,$time,$secondLevelDivide,1)";
//                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '给上上级分sql' . $grandfatherDividend . PHP_EOL, FILE_APPEND);
//
//                    $grandfatherResult = mysqli_query($link, $grandfatherDividend);
//                    //每笔信用卡订单给爷爷提成0.5
//                    $grandfatherticheng = "insert into `jd_dividend` (`uid`,`danhao`,`trade_no`,`shou`,`parent`,`total`,`type`,`level`,`time`,`divide`,`status`) values ('{$grandfatherUid}','{$danhao}','{$trade_no}','{$shou}','{$grandfatherUid}','0.5',3,2,$time,$secondLevelDivide,1)";
//                    file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . ' 给上上级提成0.5sql: '. $grandfatherticheng . PHP_EOL, FILE_APPEND);
//
//                    $grandfathertichengResult = mysqli_query($link, $grandfatherticheng);
//                    if ($grandfathertichengResult) {
//                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '给上上级提成0.5成功' . PHP_EOL, FILE_APPEND);
//                    } else {
//                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '给上上级提成0.5失败' . PHP_EOL, FILE_APPEND);
//                    }
//
//                    if ($grandfatherResult) {
//                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '给上上级分润成功' . PHP_EOL, FILE_APPEND);
//                    } else {
//                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '给上上级分润失败' . PHP_EOL, FILE_APPEND);
//                    }

                    /** 爷爷级 end */

                    if ($id4 > 0) {
                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '分润成功' . PHP_EOL, FILE_APPEND);

                        echo success;
                    } else {
                        file_put_contents("xykResult.txt", date('Y-m-d H:i:s') . '分润失败' . PHP_EOL, FILE_APPEND);

                        echo fail;
                    }

                }
            } else {
                file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'平台用户余额修改失败' . PHP_EOL, FILE_APPEND);
                echo fail;
            }

        } else {
            file_put_contents("xykResult.txt", date('Y-m-d H:i:s').'订单状态修改失败' . PHP_EOL, FILE_APPEND);
            echo fail;
        }

        /*
        {"gmt_create":"2017-12-11 09:50:03",
        "charset":"UTF-8",
        "seller_email":"nnxxkj007@126.com",
        "subject":"\u6709\u95f4\u5c0f\u5e97",
        "sign":"WkS\/pxdee6z127qutpve8Dw5NhZFs4llrPcmVcx2G2m39K7ya762qHU+5l84tC44rxhWokb6KTNNttcnlvDa4VLHb5mqTPgDcXAKkqWkzKiJkwHbI5hrNNqG1QkHV1IGkRkHwViju4ywz8ot9kMh3wm5C4es0csfb9tcVJJryl8=",
        "buyer_id":"2088312387000015",
        "invoice_amount":"0.10",
        "notify_id":"f4c3330419b6b959aa8486b8909a546g2x",

        "fund_bill_list":"[{\"amount\":\"0.10\",
                            \"fundChannel\":\"ALIPAYACCOUNT\"
                          }]",
        "notify_type":"trade_status_sync",
        "trade_status":"TRADE_SUCCESS",
        "receipt_amount":"0.10",
        "buyer_pay_amount":"0.10",
        "app_id":"2017060107400865",
        "sign_type":"RSA",
        "seller_id":"2088621910829161",
        "gmt_payment":"2017-12-11 09:50:03",
        "notify_time":"2017-12-11 09:50:03",
        "version":"1.0",
        "out_trade_no":"20171211094828311648",
        "total_amount":"0.10",
        "trade_no":"2017121121001004010541601561",
        "auth_app_id":"2017060107400865",
        "buyer_logon_id":"173****3411",
        "point_amount":"0.00"}

        */


    }


}



